<?php

class BannerController extends BackendController
{
    /**
     * @param $id
     * @throws CHttpException
     */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Banner;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Banner']))
		{
			$model->attributes=$_POST['Banner'];
			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Create Success'));
				$this->redirect(array('index','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

    /**
     * @param $id
     * @throws CHttpException
     */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Banner']))
		{
			$model->attributes=$_POST['Banner'];
			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Update Success'));
				$this->redirect(array('index','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

    /**
     * @param $id
     * @throws CDbException
     * @throws CHttpException
     */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria = new CDbCriteria();
        $criteria->order = 'id DESC';
        $criteria->condition = 'type=2';
        $count = Banner::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 13;
        $pages->applyLimit($criteria);
        $list = Banner::model()->findAll($criteria);
        $this->render('index', array('count'=>$count,'list' => $list, 'pages' => $pages));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Banner('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Banner']))
			$model->attributes=$_GET['Banner'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}


    /**
     * Banners详情页
     * @param $id
     */
    public function actionBanners($id)
    {
        $criteria = new CDbCriteria();
        $criteria->order = 'id DESC';
        $criteria->condition = 'id='.$id.'';
        $count = Banner::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 13;
        $pages->applyLimit($criteria);
        $list = Banner::model()->findAll($criteria);
        $this->render('bannersIndex', array('count'=>$count,'list' => $list, 'pages' => $pages, 'id'=>$id));
    }

    /**
     * 创建Banners
     * @param $id
     * @throws CHttpException
     */
    public function actionBannersCreate($id)
    {
        $data = Banner::model()->findByPk($id);
        if($data===null) throw new CHttpException(404,'The requested page does not exist.');
        $model = new BannerForm();
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['BannerForm']))
        {
            $file = CUploadedFile::getInstance($model, 'img'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $img = XUpload::createFile($file,'');
            }

            $valueTemp[] = array(
                'img'=>$img,
                'link'=>$_POST['BannerForm']['link'],
                'desc'=>$_POST['BannerForm']['desc'],
                'target'=>$_POST['BannerForm']['target'],
                'sort'=>$_POST['BannerForm']['sort'],
                'status'=>$_POST['BannerForm']['status'],
                'sign'=>uniqid(),
            );

            $data->value = json_decode($data->value,true);
            $_POST['BannerForm']['value'] = json_encode(array_merge($data->value,$valueTemp),true);
            $model = Banner::model()->updateByPk($id,array('value'=>''.$_POST['BannerForm']['value'].''));
            if($model){
                Yii::app()->user->setFlash('success', Yii::t('app', 'Create Success'));
                $this->redirect(array('banner/banners','id'=>$id));
            }
        }

        $this->render('bannersCreate',array(
            'model'=>$model,
            'data'=>$data,
        ));
    }

    /**
     * 更新广告
     * @param $id
     * @param $sign
     * @throws CException
     * @throws CHttpException
     */
    public function actionBannersUpdate($id,$sign)
    {
        $data = Banner::model()->findByPk($id);
        if($data===null) throw new CHttpException(404,'The requested page does not exist.');
        //取出当前ID对应数据
        $data->value = (json_decode($data->value));
        //var_dump($data->value);
        if(is_array($data->value)){
            foreach ($data->value as $key=>$value){
                if($data->value[$key]->sign==$sign){
                    $v = $value;
                }
            }
        }

        //创建对象
        $model = Yii::createComponent(array(
            'class'=>'application.modules.backend.models.BannerForm',
            'img'=>$v->img,
            'target'=>$v->target,
            'link'=>$v->link,
            'sort'=>$v->sort,
            'status'=>$v->status,
            'desc'=>$v->desc,
            'sign'=>$v->sign,
        ));

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['BannerForm']))
        {
            $file = CUploadedFile::getInstance($model, 'img'); //获得一个CUploadedFile的实例
            if ($file) { // 判断实例化是否成功
                $img = XUpload::createFile($file,'');
            }
            $valueTemp[] = array(
                'img'=>$img,
                'link'=>$_POST['BannerForm']['link'],
                'desc'=>$_POST['BannerForm']['desc'],
                'target'=>$_POST['BannerForm']['target'],
                'sort'=>$_POST['BannerForm']['sort'],
                'status'=>$_POST['BannerForm']['status'],
                'sign'=>$sign,
            );
            $newData = json_decode(json_encode($data->value),true);

            if( is_array($newData) ) {
                foreach ($newData as $key => $value) {
                    if($value['sign'] == $sign){
                        unset($newData[$key]);
                    }
                }
            }

            $_POST['BannerForm']['value'] = json_encode(array_merge($newData,$valueTemp));
            $modelUpdate = Banner::model()->updateByPk($id,array('value'=>''.$_POST['BannerForm']['value'].''));
            if($modelUpdate){
                Yii::app()->user->setFlash('success', Yii::t('app', 'Update Success'));
                $this->redirect(array('banner/banners','id'=>$id));
            }
        }

        $this->render('bannersUpdate',array(
            'model'=>$model,
            'data'=>$data,
        ));
    }

    /**
     * 删除广告
     * @param $id
     * @param $sign
     * @throws CHttpException
     */
    public function actionBannersDelete($id,$sign)
    {
        $data = Banner::model()->findByPk($id);
        if($data===null) throw new CHttpException(404,'The requested page does not exist.');
        $dataArr = json_decode($data->value,true);
        if(is_array($dataArr)){
            foreach ($dataArr as $key => $value){
                if($value['sign']==$sign){
                    unset($dataArr[$key]);
                }
            }
        }
        $modelDelete = Banner::model()->updateByPk($id,array('value'=>''.json_encode($dataArr).''));
        //删除图片
        //unlink();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('banners','id'=>$id));
    }

    /**
     * @param $id
     * @param $sign
     */
    public function actionBannersView($id,$sign)
    {
        $data = Banner::model()->findByPk($id);
        $value = json_decode($data->value);
        foreach ($value as $key => $v){
            if($v->sign == $sign){
                //$vTemp = (array)$v;
                $model = array_merge(array('id'=>$id,'name'=>$data->name,'tips'=>$data->tips),(array)$v);
            }
        }
        //将数组转为对象，两种方法，1.(object)$model,2.json_decode(json_encode($model),false)
        $model = json_decode(json_encode($model),false);
        //var_dump($model);exit;
        $this->render('bannersView',array(
            'model'=>$model,
        ));
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Banner the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Banner::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Banner $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='banner-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
